package com.vision.web.aop;

import com.vision.sensitivewdfilter.WordFilterCenter;
import com.vision.web.annotation.WordFilter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author zhongchao
 * @title
 * @Date 2017/05/26
 */
@Aspect
@Component
public class WordFilterAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // @Pointcut("execution(* com.vision.web.controller..search*(..))")

    // 定义切点Pointcut
    @Pointcut("execution(* com.vision.dao.*..*(..))")
    public void execute() {
    }


    @Around("execute()")
    public Object around(ProceedingJoinPoint pjp) {
        Object result = null;
        try {
            result = pjp.proceed(pjp.getArgs());
            Class<?> aClass = result.getClass();
            if (aClass.getSuperclass().getInterfaces()[0] == java.util.List.class) {
                @SuppressWarnings("unchecked")
                List<Object> list = (List) result;
                list.forEach(o -> Arrays.stream(o.getClass().getDeclaredFields())
                        .forEach(field -> Arrays.stream(field.getAnnotations())
                                .filter(annotation -> annotation.annotationType() == WordFilter.class)
                                .forEach(a -> {
                                            try {
                                                field.setAccessible(true);
                                                String s = (String) field.get(o);
                                                field.set(o, WordFilterCenter.doFilter(s));
                                            } catch (IllegalAccessException e) {
                                                logger.error("返回参数过滤出现异常:{}", e);
                                            }
                                        }
                                )));

            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return result;
    }
}
